package com.acoreful.ackitcloud.filter;

import cn.hutool.core.util.IdUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;


@Slf4j
@Component
@RefreshScope
@RequiredArgsConstructor
public class TraceIdFilter implements GlobalFilter, Ordered {
    public final static String LOG_TRACE_ID="traceId";
    @Value("${gateway.config.traceId.enabled:false}")
    private boolean traceIdEnable;
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        if (!traceIdEnable) {
            return chain.filter(exchange);
        }
        String traceId = IdUtil.fastUUID();
        MDC.putCloseable(LOG_TRACE_ID, traceId);
        exchange.getRequest().mutate()
                .headers(h -> h.add(LOG_TRACE_ID, traceId)).build();
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return Ordered.HIGHEST_PRECEDENCE;
    }

}
